/**
 * Copyright (C) 2009 alex <me@alex.0x08.org>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



package uber.netbsd.community.dao.gallery;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import uber.netbsd.community.dao.StructBuilder;

/**
 * Builder implementation for GalleryImage object.
 *
 * @author alex
 */
public class GalleryBuilder extends StructBuilder<GalleryImage>{

     public GalleryBuilder(GalleryImage c) {

        super(c);
    }

     /**
      * Adds image from inputstream to produced object;
      * All image type detection starts here. Will throw RuntimeException if image format is not supported
      * @param in input stream
      * @return builder
      * @throws IOException
      *
      */
     public GalleryBuilder addImageFromStream(InputStream in) throws IOException {

         ImageBuilder ib = ImageBuilder.createInstance().setSource(in);

         if (ib.isUnsupported()) {
             throw new RuntimeException("Image format is not supported");
         }
         ByteArrayOutputStream out = null;
        try {

            out = new ByteArrayOutputStream();

            ImageIO.write(ib.getSource(), "png", out);

           byte[]  img_bytes = out.toByteArray();

           this.obj.setData(img_bytes);
           this.obj.setContentType("image/png");
           this.obj.setSize(img_bytes.length);

           this.obj.setPreview(ib.scaleToProfile().getScaledAsBytes());

           

        } finally {

            if (out!=null) {
            try {

                out.close();
            } catch (Exception e) {
            }
            }

        }

         return this;
     }

    public static GalleryBuilder getInstance() {

        return getInstanceFor(new GalleryImage());
    }

    public static GalleryBuilder getInstanceFor(GalleryImage c) {

        return new GalleryBuilder(c);
    }
}
